package com.meirengu.webview.service.impl;

import com.meirengu.common.RedisClient;
import com.meirengu.service.impl.BaseServiceImpl;
import com.meirengu.utils.DateUtils;
import com.meirengu.webview.common.Constants;
import com.meirengu.webview.common.UserChannelEnum;
import com.meirengu.webview.dao.CheckCodeDao;
import com.meirengu.webview.dao.KwInterfaceConfigDao;
import com.meirengu.webview.dao.KwZhudaiFilterDao;
import com.meirengu.webview.model.KwInterfaceConfig;
import com.meirengu.webview.model.KwZhudaiFilter;
import com.meirengu.webview.model.User;
import com.meirengu.webview.model.UserInfo;
import com.meirengu.webview.service.KwAreaDataService;
import com.meirengu.webview.service.KwZhudaiFilterService;
import com.meirengu.webview.service.KwZhudaiPushService;
import com.meirengu.webview.service.UserInfoService;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

import static com.meirengu.utils.DateUtils.dateFormat;
import static java.util.Calendar.HOUR_OF_DAY;

/**
 * KwZhudaiFilter服务实现层
 *
 * @author Mao
 * @create Wed May 09 11:06:38 CST 2018
 */
@Service
public class KwZhudaiFilterServiceImpl extends BaseServiceImpl<KwZhudaiFilter> implements KwZhudaiFilterService {


    @Autowired
    private RedisClient redisClient;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private KwInterfaceConfigDao kwInterfaceConfigDao;

    @Autowired
    private KwZhudaiPushService kwZhudaiPushService;

    @Autowired
    private KwAreaDataService kwAreaDataService;

    @Autowired
    private KwZhudaiFilterDao kwZhudaiFilterDao;

    @Autowired
    private CheckCodeDao checkCodeDao;

    Logger logger = LoggerFactory.getLogger(KwZhudaiFilterServiceImpl.class);


    /**
     * 发送助贷网接口
     * 过滤条件
     * 1有房、有车、有寿险保单（满足一个或多个属性皆可）
     * 2年龄25-55岁（含）
     * 3城市
     *
     * @param userInfo
     * @param user
     * @throws Exception
     */
    public boolean sendZhuDai(UserInfo userInfo, User user) throws Exception {

        boolean sendFlag = false;
        try {
            String zhudaiIol = redisClient.get("iol-zhudai");
            if ("N".equals(zhudaiIol)) {
                String id = user.getId();
                String name = user.getName();
                String mobile = user.getMobile();
                String city = userInfo.getScity();
                Integer sex = user.getSex();

                Integer hasCar = userInfo.getCar();
                Integer housingType = userInfo.getHouse();
                Integer lifeInsurance = userInfo.getPolicy();
                BigDecimal expectAmount = userInfo.getExpectAmount();
                Integer socialSecurity = userInfo.getSocialSecurity();
                Integer fund = userInfo.getFund();
                Integer paytype = userInfo.getSalaryMethod();
                String ip = userInfo.getIp();
                Integer creditSituation = userInfo.getCredit();
                Integer weloan = userInfo.getWxloan();

                int age = 25;
                Date brithdayDate = userInfo.getBirthday();
                age = DateUtils.getAge(brithdayDate);


                KwZhudaiFilter kwZhudaiFilter = new KwZhudaiFilter();
                kwZhudaiFilter.setUserId(id);
                kwZhudaiFilter.setMobile(mobile);
                kwZhudaiFilter.setChannelCode("zhudai");
                kwZhudaiFilter.setChannelName("助贷网");

                KwInterfaceConfig kwInterfaceConfig = kwInterfaceConfigDao.findByCode("zhudai");

                boolean dataFlag = true;
                if (kwInterfaceConfig != null) {
                    if (dataFlag && "Y".equals(kwInterfaceConfig.getLimitArea())) {
                        city = city.replace("市", "");
                        String cityRange = kwInterfaceConfig.getAreaValue();
                        if (!cityRange.contains(city)) {
                            dataFlag = false;
                            kwZhudaiFilter.setSuited("N");
                            kwZhudaiFilter.setCode(UserChannelEnum.FAIL_AREA.getValue());
                            kwZhudaiFilter.setRefuseMsg("用户所在城市不满足：" + city);
                        }
                    }
/*
                    if (dataFlag) {
                        String zhudaiald = redisClient.hget("ald-zhudai", "out_limit_" + userInfo.getAreaCode());
                        if (StringUtils.isBlank(zhudaiald)) {
                            Map<String, Object> map = new HashMap<>();
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                            map.put("channelCode", "zhudai");
                            map.put("dataDate", sdf.format(new Date()));
                            map.put("areaCode", userInfo.getAreaCode());
                            List<KwAreaData> AreaDataList = kwAreaDataService.getModel(map);
                            if (AreaDataList.size() == 1) {
                                zhudaiald = AreaDataList.get(0).getOutLimit();
                            }
                        }
                        if ("Y".equals(zhudaiald)) {
                            dataFlag = false;
                            kwZhudaiFilter.setSuited("N");
                            kwZhudaiFilter.setCode(UserChannelEnum.FAIL_MAX_PUSH.getValue());
                            kwZhudaiFilter.setRefuseMsg("不再接收数据：" + city);
                        }
                    }
*/
                    if (dataFlag && "Y".equals(kwInterfaceConfig.getLimitAge())) {
                        if (age < kwInterfaceConfig.getMinAge().intValue() || age > kwInterfaceConfig.getMaxAge().intValue()) {
                            dataFlag = false;
                            kwZhudaiFilter.setSuited("N");
                            kwZhudaiFilter.setCode(UserChannelEnum.FAIL_AGE.getValue());
                            kwZhudaiFilter.setRefuseMsg("用户年龄不符合：" + age);
                        }
                    }

                    if (dataFlag && "Y".equals(kwInterfaceConfig.getLimitAmount())) {
                        if (expectAmount.intValue() < kwInterfaceConfig.getMinAmount() || expectAmount.intValue() > kwInterfaceConfig.getMaxAmount()) {
                            dataFlag = false;
                            kwZhudaiFilter.setSuited("N");
                            kwZhudaiFilter.setCode(UserChannelEnum.FAIL_LOW_AMOUNT.getValue());
                            kwZhudaiFilter.setRefuseMsg("申请贷款额度小于" + kwInterfaceConfig.getMinAmount() + "w：" + expectAmount);
                        }
                    }
                    if (dataFlag) {
                        if (kwInterfaceConfig.getHouseValue().contains(housingType.intValue() + "") ||
                                kwInterfaceConfig.getCarValue().contains(hasCar.intValue() + "") ||
                                kwInterfaceConfig.getPolicyValue().contains(lifeInsurance.intValue() + "") ||
                                kwInterfaceConfig.getFundValue().contains(fund.intValue() + "")) {

                            //名下车   1 无车   2 有车贷    3有车无贷
                            String car = "有";
                            if (hasCar.intValue() == 1) {
                                car = "无";
                            }
                            String job = "有";
                            String house = "有";
                            //名下房产  1 无房   2 有房贷   3有房无贷
                            if (housingType.intValue() == 1) {
                                house = "无";
                            }
                            String baodanIs = "有";
                            //寿险  1 无寿险   2 寿险2400以下   3 寿险2400以上
                            if (lifeInsurance.intValue() == 1) {
                                baodanIs = "无";
                            }
                            String sexStr = "男";
                            //性别 0 男    1女
                            if (sex.intValue() == 1) {
                                sexStr = "女";
                            }
                            int money = (expectAmount.divide(new BigDecimal(10000))).intValue();
                            if (money < 1) {
                                money = 1;
                            }
                            String shebao = "有";
                            //社保   0无社保   1一年以内    2一年以上
                            if (socialSecurity.intValue() == 0) {
                                shebao = "无";
                            }
                            String gongjijin = "有";
                            //住房公积金   0无公积金   1一年以内    2一年以上
                            if (fund.intValue() == 0) {
                                gongjijin = "无";
                            }
                            String isbankpay = "是";
                            //工资发放方式  1 银行转账  2 现金发放
                            if (paytype.intValue() == 2) {
                                isbankpay = "否";
                            }
                            String creditCard = "有";
                            //信用情况 1无信用卡无贷款   2有信用卡或贷款
                            if (creditSituation.intValue() == 1) {
                                creditCard = "无";
                            }

                            long timemillis = userInfo.getCreateDate().getTime();
                            /*logger.info("用户注册时间：{}",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(timemillis)));*/
                            int weili = 0;
                            if (weloan.intValue() == 1) {
                                weili = 1;
                            }

                            String checkCode = getCheckCodeByMobile(mobile);

                            Integer code = kwZhudaiPushService.applyLoan(name, mobile, city, car, age, job,
                                    house, baodanIs, sexStr, money, shebao, gongjijin,
                                    isbankpay, ip, creditCard, null, timemillis + "", weili, checkCode);
                            kwZhudaiFilter.setSuited("Y");
                            kwZhudaiFilter.setCode(UserChannelEnum.PASS.getValue());
                            /*推送接口后修改限制数量*/
                            userInfoService.updateLimitNum(code, "zhudai", user);
                            /*userInfoService.updateAreaLimit(code, "zhudai", userInfo, user);*/
                            if (code.intValue() == Constants.BUSINESS_STATUS_SUCCESS) {
                                sendFlag = true;
                            }
                        } else {
                            dataFlag = false;
                            kwZhudaiFilter.setSuited("N");
                            kwZhudaiFilter.setCode(UserChannelEnum.FAIL_O2O.getValue());
                            kwZhudaiFilter.setRefuseMsg("无车：" + hasCar.intValue() + " 无房：" + housingType.intValue() +
                                    " 无保单：" + lifeInsurance.intValue() + " 无公积金：" + fund.intValue());
                        }
                    }
                }
                insert(kwZhudaiFilter);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(ExceptionUtils.getFullStackTrace(e));
        }
        return sendFlag;
    }

    /**
     * 根据手机号获取验证码
     */
    private String getCheckCodeByMobile(String mobile) {
        Map<String, Object> params = new HashMap<>();
        params.put("mobile", mobile);
        params.put("orderBy", "id");
        params.put("order", "DESC");

        Calendar calendar = Calendar.getInstance();

        //25小时前
        calendar.add(HOUR_OF_DAY, -25);
        params.put("startTime", dateFormat.format(calendar.getTime()));
        List<Map<String, Object>> checkCodeList = checkCodeDao.getByPage(params);
        if (checkCodeList != null && checkCodeList.size() > 0) {
            return checkCodeList.get(0).get("code").toString();
        }

        //48小时前
        calendar.add(HOUR_OF_DAY, -23);
        params.put("startTime", dateFormat.format(calendar.getTime()));
        checkCodeList = checkCodeDao.getByPage(params);
        if (checkCodeList != null && checkCodeList.size() > 0) {
            return checkCodeList.get(0).get("code").toString();
        }

        params.remove("startTime");
        checkCodeList = checkCodeDao.getByPage(params);
        if (checkCodeList != null && checkCodeList.size() > 0) {
            return checkCodeList.get(0).get("code").toString();
        }

        return "";
    }

    @Override
    public List<KwZhudaiFilter> getModel(Map map) throws Exception {
        return kwZhudaiFilterDao.getModel(map);
    }
}
